// pages/lawyerTool/zqjs/zqjs.js
import formatDate from '../../../utils/util.js';
import postData from '../../../utils/vendor/common/common.js';
const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    targetAmount: "",
    showClear: false,
    // hanziNum: "",
    // lawyerFeeShow: false,
    // lawyerDet: false,
    interestType:"银行同期利率",
    // interestMult:"1倍",
    interestMultValue:1,
    interestArea:"年利率",
    rate:4.75,
    startDate:'请选择',
    currentDate:"",
    startDate1: '请选择',
    currentDate1: "",
    interestValue: 0,//利息
    tempInterestValue: 0,
    deferredPayment:0,//延迟履行金
    tempDeferredPayment:0,
    otherAmount:"",//其它金额
    showOthClear: false,
    allPayment: 0,//总金额
    showBtn:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // console.log("options=======", options)
    var format = formatDate.timetrans(new Date(),"day");
    if (options.id == 'zqjs') {
      this.setData({
        showBtn: true
      });
    }
    this.setData({
      currentDate: format,
      currentDate1: format
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    // this.tool = this.selectComponent("#tool");
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  //点击显示介绍信息
  showIntroduce: function () {
    wx.navigateTo({
      url: '../det/det',
    })
  },

  //触发输入金额
  targetAmountChange: function (e) {
    // console.log(e.detail.value);
    let _this = this;
    let value = e.detail.value;
    if (isNaN(value * 1) || value * 1 < 0 || value == "") {
      _this.setData({
        showClear: false,
        // lawyerFeeShow: false,
        // lawyerDet: false,
        targetAmount: "",
        // hanziNum: "",
        interestValue:0
      });
    } else {
      // let hanziNum = postData.numToHanzi(value);
      if (_this.judgePointerTwo(value)){
        value = Math.floor(value * 100) / 100
      }
      _this.setData({
        showClear: true,
        // lawyerFeeShow: true,
        // lawyerDet: true,
        // hanziNum: hanziNum,
        targetAmount: value
      });
      if (_this.data.startDate != "请选择" && _this.data.startDate != "" && _this.data.rate != "") {
          if (_this.data.interestType == "约定利率"){
            _this.calculateInterest();
          } else if (_this.data.interestType == "银行同期利率"){
            _this.calculateByLoop();
          }
        }
      //计算延迟履行金
      if (_this.data.startDate1 != "请选择" && _this.data.startDate1) {
        _this.calcuateDefferdPayment();
      }
    }
  },

  //判断是否位数字
  judeNum: function (value) {
    var patrn = /^(-)?\d+(\.\d+)?$/;
    if (patrn.exec(value) == null || value == "") {
      return false
    } else {
      return true
    }
  },

  //点击清空本金
  clearNum: function () {
    let allPayment = 0;
    if (this.data.otherAmount != ""){
      allPayment = this.data.otherAmount *1;
    }
    this.setData({
      targetAmount: "",
      showClear: false,
      // lawyerFeeShow: false,
      // lawyerDet: false,
      interestValue: 0,
      deferredPayment:0,
      allPayment: allPayment
    });
  },

  //点击显示利息方式
  showInterestType: function(){
    let _this = this;
    wx.showActionSheet({
      itemList: ['约定利率', '银行同期利率'],
      success: function (res) {
        // console.log(res.tapIndex)
        if (res.tapIndex == 0){
          _this.setData({
            interestType: "约定利率"
          });
          if (_this.data.targetAmount != "" && _this.data.startDate != "请选择" && _this.data.startDate != "" && _this.data.rate != "") {
            _this.calculateInterest();
          }

        } else if (res.tapIndex == 1){
          _this.setData({
            interestType: "银行同期利率"
          });
          if (_this.data.targetAmount != "" && _this.data.startDate != "请选择" && _this.data.startDate != "") {
            _this.calculateByLoop();
          }
        }
      },
      fail: function (res) {
        console.log(res.errMsg)
      }
    })
  },

  //点击显示银行同期利率的倍数
  interestMultChange: function (e) {
    // console.log("利率=",e.detail.value);
    let _this = this;
    let value = e.detail.value;
    if (isNaN(value * 1) || value * 1 < 0 || value == "") {
      this.setData({
        interestMultValue: "",
        interestValue: 0
      });
    } else {
      if (_this.judgePointerTwo(value)) {
        value = Math.floor(value * 100) / 100
      }
      this.setData({
        interestMultValue: value
      });
      if (_this.data.interestType == "银行同期利率") {
          if (_this.data.targetAmount != "" && _this.data.startDate != "请选择" && _this.data.startDate != "") {
            _this.calculateByLoop();
          }
      }
    }
  },
  // showInterestMultiple: function () {
  //   let _this = this;
  //   wx.showActionSheet({
  //     itemList: ['1倍', '2倍','3倍','4倍'],
  //     success: function (res) {
  //       // console.log(res.tapIndex)
  //       let interestMult = '1倍', interestMultValue = 1;
  //       if (res.tapIndex == 0) {
  //         interestMult = '1倍';
  //         interestMultValue = 1;
  //       } else if (res.tapIndex == 1) {
  //         interestMult = '2倍';
  //         interestMultValue = 2;
  //       } else if (res.tapIndex == 2){
  //         interestMult = '3倍';
  //         interestMultValue = 3;
  //       } else if (res.tapIndex == 3) {
  //         interestMult = '4倍';
  //         interestMultValue = 4;
  //       }
  //       _this.setData({
  //         interestMult: interestMult,
  //         interestMultValue: interestMultValue
  //       });

  //       if (_this.data.interestType == "银行同期利率") {
  //         if (_this.data.targetAmount != "" && _this.data.startDate != "请选择" && _this.data.startDate != "") {
  //           _this.calculateByLoop();
  //         }
  //       }
  //     },
  //     fail: function (res) {
  //       console.log(res.errMsg)
  //     }
  //   })
  // },



  //计算类类型为银行同期利率利息方法
  calculateByLoop: function(){
    let _this = this;
    _this.setData({
      tempInterestValue: 0
    });
    //按照银行银行同期利率计算
    let endDate = _this.data.currentDate;
    let jgDate = _this.daysJia(endDate);
    let rateList = formatDate.BankRateList;
    for (let i = 0; i < rateList.length; i++) {
      let tempDate = rateList[i].date;
      let differdays = _this.judgeDifferDays(endDate, tempDate);
      if (differdays <= 0) {
        _this.loopComputation(i - 1, jgDate, 1);
        break;
      }
    }
  },

  //点击显示年息/月/日息
  showInterestArea: function(){
    let _this = this;
    wx.showActionSheet({
      itemList: ['年利率', '月利率','日利率'],
      success: function (res) {
        // console.log(res.tapIndex)
        if (res.tapIndex == 0) {
          _this.setData({
            interestArea: "年利率",
            rate:4.75
          });
        } else if (res.tapIndex == 1) {
          _this.setData({
            interestArea: "月利率",
            rate:2
          });
        } else if (res.tapIndex == 2){
          _this.setData({
            interestArea: "日利率",
            rate: 0.03
          });  
        }
        if (_this.data.targetAmount != "" && _this.data.startDate != "请选择" && _this.data.startDate != "" && _this.data.rate != ""){
          _this.calculateInterest();
        }
      },
      fail: function (res) {
        console.log(res.errMsg)
      }
    })
  },

  //触发输入利率
  rateChange: function (e) {
    // console.log("利率=",e.detail.value);
    let _this = this;
    let value = e.detail.value;
    if (isNaN(value * 1) || value * 1 < 0 || value == "") {
      this.setData({
        rate: "",
        interestValue:0
      });
    } else {
      if (_this.judgePointerTwo(value)) {
        value = Math.floor(value * 100) / 100
      }
      this.setData({
        rate: value
      });
      if (_this.data.targetAmount != "" && _this.data.startDate != "请选择" && _this.data.startDate != "") {
        _this.calculateInterest();
      }
    }
  },

  //开始日期触发
  bindStartDateChange: function (e) {
    // console.log('picker发送选择改变，携带值为', e.detail.value)
    let _this = this;
    this.setData({
      startDate: e.detail.value
    })
    if (_this.data.targetAmount != "" && _this.data.rate != "") {
      if (_this.data.interestType == "约定利率") {
        _this.calculateInterest();
      } else if (_this.data.interestType == "银行同期利率") {
        _this.calculateByLoop();
      }
    }
  },

  //当前日期触发
  bindCurrentDateChange: function (e) {
    // console.log('picker发送选择改变，携带值为', e.detail.value)
    let _this = this;
    this.setData({
      currentDate: e.detail.value
    })
    if (_this.data.targetAmount != "" && _this.data.startDate != "请选择" && _this.data.startDate != "" && _this.data.rate != "") {
      if (_this.data.interestType == "约定利率") {
        _this.calculateInterest();
      } else if (_this.data.interestType == "银行同期利率") {
        _this.calculateByLoop();
      }
    }
  },


  //开始日期触发计算延迟履行金
  bindStartDateChange1: function (e) {
    // console.log('picker发送选择改变，携带值为', e.detail.value)
    let _this = this;
    this.setData({
      startDate1: e.detail.value
    })
    //计算延迟履行金
    if (_this.data.targetAmount != "") {
      _this.calcuateDefferdPayment();
    }
  },

  //当前日期触发计算延迟履行金
  bindCurrentDateChange1: function (e) {
    // console.log('picker发送选择改变，携带值为', e.detail.value)
    let _this = this;
    this.setData({
      currentDate1: e.detail.value
    })
    //计算延迟履行金
    if (_this.data.targetAmount != "" && _this.data.startDate1 != "请选择" && _this.data.startDate1) {
      _this.calcuateDefferdPayment();
    }
  },

  //计算相隔天数
  getDateDiff:function(startDate, endDate){
    let startTime = new Date(Date.parse(startDate.replace(/-/g, "/"))).getTime();
    let endTime = new Date(Date.parse(endDate.replace(/-/g, "/"))).getTime();
    let dates = (endTime - startTime) / (1000 * 60 * 60 * 24);
    if (dates<0){
      wx.showModal({
        title: '提示',
        content: '所选日期超出当前日期',
        showCancel:false,
        confirmText:'知道了',
        success: function (res) {
          if (res.confirm) {
          } 
        }
      })
      dates = 0
    }
    return dates;
  },

  //约定利率方式计算利息
  calculateInterest: function() {
    let rate = this.data.rate;
    let time = this.data.interestArea == '年利率' ? 360 : this.data.interestArea == '月利率'?30:1;
    let diffday = this.getDateDiff(this.data.startDate, this.data.currentDate);
    let amt = this.data.targetAmount;
    // console.log("金额====", rate, time, diffday, amt)
    let interest = (rate * diffday * amt * 1) / (time * 100);
    let restAmt = interest.toFixed(2) * 1;
    this.setData({
      interestValue: restAmt
    });
    //监听总金额
    this.judgeAllPayment();
  },

  //开始计算延迟履行金
  calcuateDefferdPayment: function(){
    let flag = this.judgeMidDate();
    let amt = this.data.targetAmount;
    let startDate = this.data.startDate1;
    let rateList = formatDate.BankRateList;
    let midDate = "2014-08-01";
    // console.log("flag==",flag)
    if(flag == -1){
      this.setData({
        tempDeferredPayment: 0
      });
      //按照银行同期利率计算
      let endDate = this.data.currentDate1;
      let jgDate = this.daysJia(endDate);
      // let rateList = formatDate.BankRateList;
      for (let i = 0; i < rateList.length; i++) {
        let tempDate = rateList[i].date;
        let differdays = this.judgeDifferDays(endDate, tempDate);
        if (differdays <= 0) {
          this.loopComputation(i - 1, jgDate,2);
          break;
        }
      }
    }else if(flag == 0){
      this.setData({
        tempDeferredPayment: 0
      });
      //前部分按照银行同期利率计算后部分按照固定1.75/10000比例计算
      //先计算后部分
      let diffday = this.getDateDiff(midDate, this.data.currentDate1); 
      let afterpayAmt = (1.75 * diffday * amt * 1) / 10000;
      this.setData({
        tempDeferredPayment: afterpayAmt
      });
      //计算前部分
      let jgDate = "2014-07-31";
      // let rateList = formatDate.BankRateList;
      let xunhuan = false;
      for (let i = 0; i < rateList.length;i++){
        let tempDate = rateList[i].date;
        let differdays = this.judgeDifferDays(jgDate, tempDate);
        if (differdays <= 0 ){
          xunhuan = true;
          this.loopComputation(i-1, "2014-08-01",2);
          break;
        }
      }
      if (!xunhuan){
        let allAmt = afterpayAmt.toFixed(2) * 1;
        this.setData({
          deferredPayment: allAmt
        });
        //监听总金额
        this.judgeAllPayment();
      }
    }else if(flag == 1){
      //按照固定比例计算
      let diffday = this.getDateDiff(this.data.startDate1, this.data.currentDate1);
      let payAmt = (1.75 * diffday * amt * 1) / 10000;
      let restAmt = payAmt.toFixed(2) * 1;
      this.setData({
        deferredPayment: restAmt
      });
      //监听总金额
      this.judgeAllPayment();
    }
  },

  //监听计算总金额
  judgeAllPayment: function(){
    let allAmt = 0;
    if (this.data.otherAmount != "") {
      allAmt = this.data.otherAmount*1 + this.data.targetAmount*1 + this.data.interestValue*1 + this.data.deferredPayment*1;

    } else {
      allAmt = this.data.targetAmount*1 + this.data.interestValue*1 + this.data.deferredPayment*1;
    }
    this.setData({
      allPayment: allAmt.toFixed(2) * 1
    });
  },

  //开始循环计算银行同期利率
  loopComputation: function(flag ,date,typeBz){
    let amt = this.data.targetAmount;
    let startDate = this.data.startDate;
    if (typeBz == 2){
      startDate = this.data.startDate1;
    }

    // if (this.judgeDifferDays("2004-10-29", startDate) < 0){
    //   startDate = "2004-10-29";
    // }
    let rateList = formatDate.BankRateList;
    let dateBeforeDay = this.daysJian(date);
    let upDate = rateList[flag + 1].date;
    if (this.judgeDifferDays(upDate, startDate) >= 0) {
      let diff = this.judgeDifferDays(startDate, dateBeforeDay);
      if(diff < 0){
        wx.showModal({
          title: '提示',
          content: '所选日期超出当前日期',
          showCancel: false,
          confirmText: '知道了',
          success: function (res) {
            if (res.confirm) {
            }
          }
        })
        return
      }
      // if (diff == 0){
      //   diff = 1;
      // }
      //设置包括当天
      diff = diff + 1;
      let rate = this.getRateByDays(flag+1, diff);
      // console.log("amt==", amt)
      // console.log("rate==", rate)
      // console.log("diff==", diff)
      // console.log("typeBz==", typeBz)
      let payAmt = (amt * rate * diff * typeBz) / (360 * 100);
      //此处渲染一次金额值
      if (typeBz == 2){ //延迟履行金
        let tempDeferredPayment = this.data.tempDeferredPayment;
        let allAmt = (payAmt + tempDeferredPayment).toFixed(2) * 1;
        this.setData({
          deferredPayment: allAmt
        });
      } else if (typeBz == 1){
        //获取倍数
        let interestMultValue = this.data.interestMultValue;
        let tempInterestValue = this.data.tempInterestValue;
        let allAmt = ((payAmt + tempInterestValue) * interestMultValue).toFixed(2) * 1;
        this.setData({
          interestValue: allAmt
        });
        // console.log("tempInterestValue=", tempInterestValue)
        // console.log("allAmt=", allAmt)
      }
      //监听总金额
      this.judgeAllPayment();
    }else{
      //先计算第一阶段
      // console.log("upDate=", upDate)
      // console.log("upDdateBeforeDayate=", dateBeforeDay)
      
      let diff = this.judgeDifferDays(upDate, dateBeforeDay);
      if (diff < 0) {
        wx.showModal({
          title: '提示',
          content: '所选日期超出当前日期',
          showCancel: false,
          confirmText: '知道了',
          success: function (res) {
            if (res.confirm) {
            }
          }
        })
        return
      }
      // if (diff == 0){
      //   diff = 1;
      // }
      //设置包括当天
      diff = diff + 1;
      // console.log("diff=", diff)
      let rate = this.getRateByDays(flag+1, diff);
      let payAmt = (amt * rate * diff * typeBz) / (360 * 100);
      // console.log("amt=", amt)
      // console.log("rate=", rate)
      // console.log("diff=", diff)
      if (typeBz == 2){
        let tempDeferredPayment = this.data.tempDeferredPayment;
        let tempAllamt = tempDeferredPayment + payAmt;
        this.setData({
          tempDeferredPayment: tempAllamt
        });
      } else if (typeBz == 1){
        let tempInterestValue = this.data.tempInterestValue;
        let tempAllamt = tempInterestValue + payAmt;
        this.setData({
          tempInterestValue: tempAllamt
        });
        // console.log("tempInterestValue=", tempInterestValue)
      }
      this.loopComputation(flag + 1, upDate, typeBz);
    }
    
  },

  //计算两日期相差天数
  judgeDifferDays: function(startDate,endDate){
    // console.log("startDate=", startDate)
    // console.log("endDate=", endDate)
    
    let startTime = new Date(Date.parse(startDate.replace(/-/g, "/"))).getTime();
    let endTime = new Date(Date.parse(endDate.replace(/-/g, "/"))).getTime();
    let dates = (endTime - startTime) / (1000 * 60 * 60 * 24);
    // console.log("day=", dates)
    return dates;
  },

  //根据天数来判断利率
  getRateByDays: function(flag,days){
    let month = days*1/30;
    let rateList = formatDate.BankRateList;
    let data;
    if(month < 6){
      data = "rate1";
    }else if(month >= 6 && month < 12){
      data = "rate2";
    } else if (month >= 12 && month < 36) {
      data = "rate3";
    } else if (month >= 36 && month < 60) {
      data = "rate4";
    }else if(month >=60){
      data = "rate5";
    }
    let rate = rateList[flag][data];
    return rate;
  },


  //判断以日期为2014-08-01为节点之前按银行同期利率进行计算，之后按照1.75/10000进行计算
  judgeMidDate: function(){
    let startDate = this.data.startDate1;
    let endDate = this.data.currentDate1;
    let midDate = "2014-08-01"; 
    let flag;
    let startTime = new Date(Date.parse(startDate.replace(/-/g, "/"))).getTime();
    let endTime = new Date(Date.parse(endDate.replace(/-/g, "/"))).getTime();
    let midTime = new Date(Date.parse(midDate.replace(/-/g,"/"))).getTime();
    
    if (endTime < midTime){
      flag = -1;
    } else if (startTime >= midTime){
      flag = 1;
    } else if ((startTime < midTime) && (midTime <= endTime)){
      flag = 0;
    }
    return flag;
  },

  //获取当前日期前一天
  daysJian: function(dataStr){
    let date = new Date(Date.parse(dataStr.replace(/-/g, "/")));//获取当前时间
    date.setDate(date.getDate() - 1);//设置天数 -1 天
    let str = formatDate.timetrans(date,"day");
    return str;
  },

  daysJia: function (dataStr){
    let date = new Date(Date.parse(dataStr.replace(/-/g, "/")));//获取当前时间
    date.setDate(date.getDate() + 1);//设置天数 +1 天
    let str = formatDate.timetrans(date, "day");
    return str;
  },

  //其它金额触发
  otherAmountChange: function(e){
    let _this = this;
    let value = e.detail.value;
    if (isNaN(value * 1) || value * 1 < 0 || value == "") {
      _this.setData({
        otherAmount: "",//其它金额
        showOthClear: false
      });
    } else {
      if (_this.judgePointerTwo(value)) {
        value = Math.floor(value * 100) / 100
      }
      _this.setData({
        otherAmount: value,//其它金额
        showOthClear: true
      });
    //监听并计算总金额
      if (this.data.targetAmount !=""){
          let allAmt = value*1 + this.data.targetAmount *1 + this.data.interestValue*1 + this.data.deferredPayment *1;
          // console.log("allAmt=", allAmt)
          this.setData({
            allPayment: allAmt.toFixed(2) * 1
          });
      }
    }
  },

  //清空其他金额
  clearOthNum: function(){
    this.setData({
      otherAmount: "",//其它金额
      showOthClear: false
    });
    this.judgeAllPayment();
  },

  //判断小数点位数是否大于两位
  judgePointerTwo: function(n){
    let flag = false;
    if (n.toString().indexOf('.') > 0){
      if (n.toString().split(".")[1].length > 2) {
        flag = true;
      }
    }
    return flag;
  },
  
  // 点击去诉讼费
  // _goSSF: function () {
  //   wx.navigateTo({
  //     url: '../ssf/ssf',
  //   })
  // },

  //点击去律师费
  // _goLSF: function () {
  //   wx.navigateTo({
  //     url: '../lsf/lsf',
  //   })
  // },

  //点击债权计算
  // _goZQJS: function () {
   
  // },

  //点击回首页
  goHome: function () {
    wx.redirectTo({
      url: '../../index/index',
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  // onHide: function () {
  
  // },

  /**
   * 生命周期函数--监听页面卸载
   */
  // onUnload: function () {
  
  // },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  // onPullDownRefresh: function () {
  
  // },

  /**
   * 页面上拉触底事件的处理函数
   */
  // onReachBottom: function () {
  
  // },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log("来自页面内的转发", res.target)
    }
    return {
      title: '律师债权计算工具',
      path: 'pages/lawyerTool/zqjs/zqjs?id=zqjs',
      // imageUrl: picUrl,
      success: function (res) {
        // 转发成功
        console.log("转发成功返回数据=", res)
        wx.showShareMenu({
          // 要求小程序返回分享目标信息
          withShareTicket: true
        });
      },
      fail: function (res) {
        // 转发失败
      },
      complete: function () {

      }
    }
  }
})